package com.lytfly.demo.account.service.impl;

import cn.hutool.core.convert.Convert;
import com.lytfly.demo.account.entity.AccountUser;
import com.lytfly.demo.account.entity.FlowInfo;
import com.lytfly.demo.account.entity.SiteMessage;
import com.lytfly.demo.account.mapper.FlowInfoMapper;
import com.lytfly.demo.account.service.IAccountUserService;
import com.lytfly.demo.account.service.IFlowInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lytfly.demo.account.service.ISiteMessageService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.DelegateTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liuyuantao
 * @since 2021年07月10日 16时22分
 */
@Service
@Slf4j
public class FlowInfoServiceImpl extends ServiceImpl<FlowInfoMapper, FlowInfo> implements IFlowInfoService {
    @Autowired
    private ActFlowCommService actFlowCommService;

    @Autowired
    private IAccountUserService userService;
    /**
     * 查询用户任务
     *
     * @param userId
     * @return
     */
    @Override
    public List<Map<String, Object>> findUserTask(Integer userId) {
        List<Map<String, Object>> list = actFlowCommService.myTaskList(userId.toString());
        return list;
    }


    /**
     * 完成任务
     *
     * @param userId
     */
    @Override
    public void completeTask(String taskId, Integer userId) {
        actFlowCommService.completeProcess("同意", taskId, userId.toString());
    }

    /**
     * 任务创建事件
     *
     * @param delegateTask
     */
    @Override
    public void createTaskEvent(DelegateTask delegateTask) {
        log.info("delegateTask=={}", delegateTask);
//      负责人
        String assignee = delegateTask.getAssignee();
//      获取当前登录用户
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        AccountUser user = userService.findOneUserByName(username);
        String userId = user.getId().toString();
//      任务id
        String taskId = delegateTask.getId();
        if (!assignee.equals(userId)) {
            int type = 1;
            SiteMessage siteMessage = new SiteMessage();
            siteMessage.setUserId(Convert.toInt(assignee));
            siteMessage.setTaskId(taskId);
            siteMessage.setType(type);
            siteMessage.setIsRead(0);
            siteMessage.insert();
        }

    }

    /**
     * 查询任务详细信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<Map<String, Object>> findTaskInfo(Integer userId) {
        List<Map<String, Object>> list = actFlowCommService.myTaskInfoList(userId.toString());
        return list;
    }
}
